﻿//*** Guidance generated code ***//
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using NHibernate;
using NHibernate.Criterion;
using ProjectBase.Core;
using ProjectBase.Data;
using ProjectBase.Data.NH;
using Survey.Common;
using Survey.Common.Data;
using Survey.Entity;

namespace Survey.Data
{
    public class QuestionDao : BaseDao<Question, int, QuestionFilter>, IQuestionDao
    {
        /// <summary>
        /// Evaluates all filters and order-by clauses
        /// and returns sorted list (IEnumerable) of 'Question' entities
        /// </summary>
        /// <param name="filter">Isearch&lt;Question&gt; containing QuestionFilter not-null instance</param>
        /// <returns>IEnumerable of Question entities matching the searching criteria</returns>
        public override IEnumerable<Question> Find(QuestionFilter filter)
        {
            // Equal
            Criteria.AddCompare(() => filter.IdExact); // Searches for exact ID
            Criteria.AddEqual(() => filter.TitleExact); // Exact match for Title (accept string.Empty)
            Criteria.AddEqual(() => filter.DescriptionExact); // Exact  ...


            // Like
            Criteria.AddLike(() => filter.Title);
            Criteria.AddLike(() => filter.Description);

            Criteria.AddCompare(() => filter.ValidUntil); // Exact  ...
            Criteria.AddCompare(() => filter.ValidUntilFrom);
            Criteria.AddCompare(() => filter.ValidUntilTo);

            Criteria.AddCompare(() => filter.IsApproved);

            AddAnswerSearch(Criteria, filter);

            return GetListByCriteria(filter);
        }

        protected void AddAnswerSearch(ICriteria criteria, QuestionFilter filter)
        {
            if (filter.AnswerTitle.IsEmpty()
               && filter.AnswerDescription.IsEmpty())
            {
                return;
            }

            var innerFilter = CreateAnswerFilter();
            innerFilter.AddFilterString("Title", filter.AnswerTitle);
            innerFilter.AddFilterString("Description", filter.AnswerDescription);

            //Criteria.Add(new InnerSelectCriteria(innerFilter));
        }

        #region Filters

        protected virtual InnerFilter CreateAnswerFilter()
        {
            return new InnerFilter
            (
                tableName: "Answer",
                selectColumnName: "QuestionId",
                whereColumnName: "AnswerId"
            );
        }

        #endregion Filters
    }
}